package com.longdaji.decoration.ui.activitiesOfMine.accountManagement.changePhone;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.longdaji.decoration.DecorationApplication;
import com.longdaji.decoration.R;
import com.longdaji.decoration.base.BaseActivity;
import com.longdaji.decoration.bean.Account;
import com.longdaji.decoration.ui.activitiesOfMine.accountManagement.AccountManagementActivity;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class ChangePhoneActivity extends BaseActivity implements ChangePhoneContract.View {

    @Inject
    ChangePhoneContract.Presenter mPresenter;
    @BindView(R.id.tv_tool_title)
    TextView tvTitle;
    @BindView(R.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R.id.btn_confirm)
    Button btnConfirm;
    @BindView(R.id.et_code)
    EditText etCode;

    private long totalTime = 60;
    private Disposable disposable;

    private Account account;
    private String newTelephone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_phone);
        setUnBinder(ButterKnife.bind(this));

        if (mPresenter != null)
            mPresenter.setView(this);
        tvTitle.setText("修改手机号");

        initView();

    }

    private void initView() {
        account = Account.getInstance();
        newTelephone = getIntent().getStringExtra("newTelephone");

        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() != 0 && !btnConfirm.isEnabled()) {
                    btnConfirm.setEnabled(true);
                } else if (editable.length() == 0) {
                    btnConfirm.setEnabled(false);
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
        super.onDestroy();
        if (mPresenter != null)
            mPresenter.detachView();
    }

    @OnClick({R.id.rl_tool_back, R.id.tv_get_code, R.id.btn_confirm})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_tool_back:
                finish();
                break;
            case R.id.tv_get_code:
                mPresenter.onGetCodeClick(newTelephone);
                break;
            case R.id.btn_confirm:
                mPresenter.onConfirmClick(newTelephone, etCode.getText().toString());
                break;
            default:
                break;
        }
    }

    @Override
    public void showSendVerification() {
        calculateTime();
        toast("验证码已发送");
    }

    private void calculateTime() {
        tvGetCode.setEnabled(false);
        Observable.interval(1000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        if (totalTime == 1) {
                            disposable.dispose();
                            tvGetCode.setText("重新发送");
                            tvGetCode.setEnabled(true);
                            return;
                        }
                        totalTime -= 1;
                        tvGetCode.setText(totalTime + "s");

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void showResult(boolean isSucceed) {
        if (isSucceed) {
            account.setTelephone(newTelephone);
            toast("电话修改成功");
            // TODO: 2018/4/27 0027 这里还要finish掉stepOne
            Intent intent = new Intent();
            intent.setClass(ChangePhoneActivity.this, AccountManagementActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
//            DecorationApplication.destroySelectedActivities();
//            finish();
        } else {
            toast("修改失败");
        }
    }

    @Override
    public void showIllegalTelephone() {
        toast("不合法的手机号码");
    }

    @Override
    public void showCodeError() {
        Toast.makeText(this, "验证码错误", Toast.LENGTH_SHORT).show();
    }
}
